<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 80%; margin-left: 50px">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="姓名" prop="realname">
            <el-input v-model="temp.realname" />
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="temp.username" />
          </el-form-item>
          <el-form-item label="上级部门" prop="organizationId">
            <system-organization v-model="temp.organizationId" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="头像" prop="portrait">
            <el-upload :action="''" :auto-upload="false" :show-file-list="false" :on-change="handleChange" class="avatar-uploader">
              <el-image v-if="flag" style="width: 100%; height: 100%" :src="url"> </el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="temp.email" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="temp.phone" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="temp.id === undefined" label="初始密码" prop="password">
            <el-input v-model="temp.password" type="password" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可否登录" prop="status">
            <el-radio v-for="item in dictList('sf')" :key="'type' + item.label" v-model="temp.status" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
      <el-button v-permission="['sys:user:update']" type="primary" :loading="loading" @click="dialogStatus === 'create' ? createData() : updateData()">
        {{ $t('table.confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createUser, updateUser } from '@/api/sys/user'
import { fetchOrganizationList } from '@/api/sys/organization'
import SystemOrganization from '@/components/System/systemOrganization'
import { fetchUser } from '@/api/sys/user'
import UploadImage from '@/components/Upload/uploadImage'
import permission from '@/directive/permission/permission'
import { getToken } from '@/utils/auth'
import { geturl } from '@/api/sys/user'
import { EventBridger } from '@/utils/event-bus.js'
export default {
  name: 'UserForm',
  directives: { permission },
  components: { UploadImage, SystemOrganization },
  data() {
    return {
      url: '',
      flag: false,
      imageList: [],
      resultUrl: undefined,
      myHeaders: { access_token: getToken() },
      uploadImageUrl: '',

      treeList: [],
      treeProps: {
        value: 'id',
        label: 'name',
      },
      organizationIds: undefined,
      temp: {},
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '创建用户',
      },
      rules: {
        realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        organizationId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        status: [{ required: true, message: '请选择可否登录', trigger: 'change' }],
      },
    }
  },

  methods: {
    fun() {
      geturl({
        params: {
          userId: this.temp.id,
        },
      }).then((res) => {
        console.log(res)
        if (res.data.code == 0) {
          this.flag = true
          this.url = res.data.msg
        }
      })
    },
    handleChange(file) {
      this.onChange(file.raw)
    },
    onChange(file) {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        this.url = e.target.result
        // 创建Base64 URL for preview
        this.flag = true
      }
    },
    // dataUrltoBlod(base64String) {
    //   // 移除Base64字符串中的非法字符和可能的填充字符
    //   base64String = base64String.replace(/[^A-Za-z0-9+/]/g, '')

    //   // 补全Base64字符串长度至4的倍数
    //   while (base64String.length % 4 !== 0) {
    //     base64String += '='
    //   }

    //   // 解码Base64字符串为二进制数据
    //   var binaryString = atob(base64String)
    //   var len = binaryString.length
    //   var bytes = new Uint8Array(len)

    //   for (var i = 0; i < len; ++i) {
    //     bytes[i] = binaryString.charCodeAt(i)
    //   }

    //   return bytes.buffer
    // },
    // dataUrltoBlod(data) {
    //   var arr = data.split(','),
    //     mime = arr[0].match(/:(.*?);/)[1],
    //     bstr = atob(arr[1]),
    //     n = bstr.length,
    //     u8arr = new Uint8Array(n)
    //   while (n--) {
    //     u8arr[n] = bstr.charCodeAt(n)
    //   }

    //   return new Blob([u8arr], {
    //     type: mime,
    //   })
    // },
    dataUrltoBlod(dataurl) {
      // 分割data URL以获取编码前的媒体类型和Base64编码数据
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1] // 提取MIME类型
      var bstr = atob(arr[1]) // 将Base64数据解码为二进制字符串
      var n = bstr.length
      var u8arr = new Uint8Array(n) // 创建用于存储解码后二进制数据的Uint8Array

      // 填充Uint8Array
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }

      // 通过Uint8Array创建Blob对象
      return new Blob([u8arr], { type: mime })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    getList() {
      this.$emit('refreshList')
    },
    getTreeList() {
      this.listLoading = true
      fetchOrganizationList(this.listQuery).then((response) => {
        this.treeList = response.data.data
        this.listLoading = false
      })
    },
    resetTemp() {
      this.loading = false
      this.temp = {
        id: undefined,
        realname: undefined,
        portrait: undefined,
        phone: undefined,
        job: undefined,
        file: undefined,
        salt: undefined,
        username: undefined,
        password: undefined,
        organizationId: undefined,
        organization: {
          id: undefined,
        },
      }
    },
    handleCreate() {
 
      this.resetTemp()
      this.flag = false
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.username.length < 4) {
            this.$message.error('用户名长度不能小于4')
            return
          }
          this.loading = true
          console.log(this.temp, 'this.tempthis.temp')
          var formData = new FormData()
          formData.append('realname', this.temp.realname)
          formData.append('tenantId', '00000000')
          formData.append('username', this.temp.username)
          formData.append('password', this.temp.password)
          formData.append('phone', this.temp.phone)
          formData.append('status', this.temp.status)
          formData.append('organizationId', this.temp.organizationId)
          // 其他需要上传的字段也可以这样添加
          // 注意，这里的'file'应该与后端接口接收文件的参数名保持一致
          if (this.url) {
            var blob = this.dataUrltoBlod(this.url) // 将Base64转换为Blob
            formData.append('file', blob, 'filename.jpg') // 添加文件
          }

          createUser(formData)
            .then((response) => {
              this.loading = false
              if (response.data.code === 0) {
                this.getList()
                this.dialogFormVisible = false
                this.$message.success(response.data.msg)
              } else {
                this.$message.error(response.data.msg)
              }
            })
            .catch((error) => {
              this.loading = false
              console.error('Upload failed:', error)
            })
        }
      })
    },

    handleUpdate(id) {
    
      this.resetTemp() // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      fetchUser(id).then((response) => {
        if (response.data.code === 0) {
          this.temp = response.data.data
          console.log(this.temp)
          this.fun()
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          // this.temp.file = this.dataUrltoBlod(this.url)

          var formData = new FormData()
          formData.append('id', this.temp.id)
          formData.append('realname', this.temp.realname)
          formData.append('username', this.temp.username)
          formData.append('password', this.temp.password)
          formData.append('phone', this.temp.phone)
          formData.append('salt', this.temp.salt)
          formData.append('tenantId', '00000000')
          formData.append('status', this.temp.status)
          formData.append('organizationId', this.temp.organizationId)
          // 其他需要上传的字段也可以这样添加
          // 注意，这里的'file'应该与后端接口接收文件的参数名保持一致
          if (this.url) {
            var blob = this.dataUrltoBlod(this.url) // 将Base64转换为Blob
            formData.append('file', blob, 'filename.jpg') // 添加文件
          }
          updateUser(formData).then((response) => {
            this.loading = false
            if (response.data.code === 0) {
              this.dialogFormVisible = false
              this.getList()
              this.fun()

              this.$message.success(response.data.msg)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
    },
  },
}
</script>

<style scoped></style>
